package com.citytransport.prokopjuk.connectDB;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

import org.apache.log4j.Logger;

import com.citytransport.prokopjuk.dao.DAOVehicle;

public class ConnectionPool {
    private static ConnectionPool connectionPool = null;
    private int maxConections;
    private int connectionUsed;
    private Connection[] pool;
    private Properties dbProperties = new Properties();
    static Logger logger = Logger.getLogger(ConnectionPool.class.getName());

    private ConnectionPool() {
	try {
	    dbProperties.load(ConnectionPool.class
		    .getResourceAsStream("/db/db.properties"));
	} catch (IOException e1) {
	    logger.error(e1);
	}
	maxConections = 10;
	connectionUsed = 0;

	pool = new Connection[maxConections];
	for (int i = 0; i < maxConections; i++) {
	    try {
		pool[i] = DriverManager.getConnection(dbProperties
			.getProperty("url"), dbProperties.getProperty("user"),
			null);
	    } catch (SQLException e) {
		logger.error(e);
	    }
	}
	logger.info("initialized ConnectionPool");
    }

    synchronized public static ConnectionPool getConnectionPool() {

	if (connectionPool == null)
	    connectionPool = new ConnectionPool();

	return connectionPool;
    }

    // TODO Wait until connectionUsed == maxConnection;
    // TODO wait() - notify()
    synchronized public Connection getConnection() {
	boolean flagStopSearch = false;
	Connection toReturn = null;
	while (!flagStopSearch) {
	    for (int i = 0; i < maxConections; i++) {
		if (pool[i] != null) {
		    toReturn = pool[i];
		    pool[i] = null;
		    connectionUsed++;
		    flagStopSearch = true;
		}
	    }
	}
	logger.info("get connection from ConnectionPool");
	return toReturn;
    }

    synchronized public void returnConnecction(Connection con) {
	boolean flagSearchStop = false;
	while (!flagSearchStop) {
	    for (int i = 0; i < maxConections; i++) {
		if (pool[i] == null) {
		    pool[i] = con;
		    con = null;
		    connectionUsed--;
		    flagSearchStop = true;
		}
	    }
	}
	logger.info("connection returned");
    }

    private void closeAllConnections() {
	for (Connection con : pool) {
	    if (con != null) {
		try {
		    con.close();
		} catch (SQLException e) {

		}
	    }
	}
    }

    public void closePool() {
	closeAllConnections();
	pool = null;
    }
}
